package com.example.dubbo.order.core.service;

import com.alibaba.fastjson.JSON;
import com.example.dubbo.account.api.AccountService;
import com.example.dubbo.order.api.OrderService;
import com.example.dubbo.order.api.dto.OrderDTO;
import com.example.dubbo.order.core.dao.OrderMapper;
import com.example.dubbo.order.core.dao.data.OrderDO;
import com.example.dubbo.order.core.utils.Converter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.UUID;

@Slf4j
@DubboService
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @DubboReference
    private AccountService accountService;

    @Override
    public OrderDTO create(String userId, String commodityCode, int orderCount) {
        int orderMoney = calculate(commodityCode, orderCount);
        // 扣减账户余额
        accountService.debit(userId, orderMoney);

        System.out.println(1 / 0);

        OrderDO orderDO = new OrderDO();
        orderDO.setOrderId(UUID.randomUUID().toString());
        orderDO.setUserId(userId);
        orderDO.setCommodityCode(commodityCode);
        orderDO.setCount(orderCount);
        orderDO.setMoney(orderMoney);
        int insert = orderMapper.insert(orderDO);
        log.info("orderMapper.insert, orderDO={}, insert={}", JSON.toJSONString(orderDO), insert);
        return Converter.convert(orderMapper.getById(orderDO.getId()), OrderDTO.class);
    }

    private int calculate(String commodityCode, int orderCount) {
        return 3 * orderCount;
    }
}
